<template>
  <div>
    <!-- 预览 -->
    <div class="previewPageWrap">
      <page ref="page" v-if="visible" class="previewPage"
        :options="options"
        :options-new="options"
      />
      <pagePics ref="pagePics" v-if="previewPagePicsShow" class="previewPagePics"
        :options="options"
        :pictures="extraPicsInitArr"
      />
    </div>
    <!-- 计算预览 -->
    <div ref="renderPage" id="renderPage">
      <template v-if="renderPageShow">
        <page
          :product-name="productName"
          :options="options"
          :options-new="item"
          :index="index + 1"
          :length="optionData.length"
          :key="index"
          v-for="(item, index) in optionData"
        />
      </template>
      <template v-if="renderPagePicsShow">
        <pagePics ref="pagePics"  class="previewPagePics"
          :product-name="productName"
          :options="options"
          :pictures="item"
          :index="index + 1 + optionData.length"
          :length="optionData.length + picturesData.length"
          :key="index"
          v-for="(item, index) in picturesData"
        />
      </template>
      <NoData v-if="picturesData.length === 0 && optionData.length === 0"/>
    </div>
  </div>
</template>

<script>
import Page from './page'
import pagePics from './pagePics'
import _ from "lodash";
import NoData from "@/components/NoData";
export default {
  components: {
    Page,
    pagePics,
    NoData,
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    },
    productName: {
      type: String,
      default: ''
    },
    options: {
      type: Object
    }
  },
  computed: {
    curOption(){
      return _.cloneDeep(this.options);
    },
  },
  data() {
    return {
      current: 1,
      renderPageShow: false,
      previewPagePicsShow: false,
      renderPagePicsShow: false,
      paginationShow: false,
      extraPicsArr: [],
      extraPicsInitArr: [],
      picturesData: [],
      optionDataArr: [],
      optionData: [
        /* {
          bomData: [],
          sourceData: [],
          gramData: [],
          stepData: [],
        } */
      ],
      tableDataIndexMap: {
        // 
      },
    }
  },
  computed: {
    optionMapData(){
      return {
        bomData: this.options.bomData,
        sourceData: this.options.sourceData,
        gramData: this.options.gramData,
        stepData: this.options.stepData,
      }
    }, 
  },
  watch: {
  },
  mounted() {
  },
  methods: {
    paginationRefresh(){
    },
    getDomHeight(arg){
      let h = 0;
      const curDom = document.querySelector(arg);
      if ( curDom ){
        h = curDom.offsetHeight
      }
      return h;
    },
    getDomWidth(arg){
      let w = 0;
      const curDom = document.querySelector(arg);
      if ( curDom ){
        w = curDom.offsetWidth
      }
      return w;
    },
    imgOnloadFinish(){

    },
    calculatePics(argDomStr,execute){
      const that = this;
      // 计算图片容器高度
      let picturesConH = that.getDomHeight(argDomStr);
      picturesConH -= 10;
      picturesConH = 692; // 不能动态获取
      // 减去padding
      // 计算图片容器宽度
      let picturesConW =  that.getDomWidth(argDomStr);
      // 减去padding
      picturesConW -= 10;
      let spilitImgArr = []; // [[img,img],[img]]
      let spilitArrIndex = 0;
      let startIndex = 0;
      let allImgLoadDom = document.querySelectorAll(`${argDomStr} img`);
      let imgTotal = allImgLoadDom.length;
      let imgCon = [];
      let promiseAll = [];
      // 检测图片全部加载完
      for(var i = 0 ; i < imgTotal ; i++){
        promiseAll[i] = new Promise((resolve, reject) => {
          imgCon[i] = new Image();
          imgCon[i].src = allImgLoadDom[i].src;
          imgCon[i].onload = function(){
            //第i张图片加载完成
            resolve();
          }
        });
      }
      //全部图片加载完成 计算图片要摆放多少行
      Promise.all(promiseAll).then(()=>{
        let allImgDom = document.querySelectorAll(`${argDomStr} img`);
        allImgDom = Array.from(allImgDom);
        allImgDom.forEach((element, index) =>{
          let curImgW = element.offsetWidth;
          let curImgH = element.offsetHeight;
          const curImgArr = allImgDom.slice(startIndex,index+1);
          const curImgWidthArr = curImgArr.map( el => el.offsetWidth);
          let sumW = curImgWidthArr.reduce((total, num) => total + num);
          if ( sumW > picturesConW ){
            spilitArrIndex++;
            if (!spilitImgArr[spilitArrIndex]){
              spilitImgArr[spilitArrIndex] = [element];
            }
          }else{
            if(spilitImgArr[spilitArrIndex]){
              spilitImgArr[spilitArrIndex].push(element);
            }else {
              spilitImgArr[spilitArrIndex] = [element];
            }
          }
        });
        console.log(spilitImgArr);

        // 计算一页可以摆放多少行
        let sumHeight = 0;
        let pageImageArr = [];
        let pageIndex = 0;
        spilitImgArr.forEach((element, index) =>{
          const curImgHeightArr = element.map( element => element.offsetHeight);
          const curRowHeight = Math.max(...curImgHeightArr);
          sumHeight += curRowHeight;
          if ( sumHeight > picturesConH){
            // 把临界（第一次超过时）上一次最后一元素放到这一次的开始
            /* if ( (sumHeight - curRowHeight) < picturesConH ){
              const popElement = pageImageArr[pageIndex].slice(-1);
              pageImageArr[pageIndex].pop();
              pageIndex++;
              pageImageArr[pageIndex] = [popElement, element];
            }else {
              pageIndex++;
              pageImageArr[pageIndex] = [element];
            } */
            pageIndex++;
            pageImageArr[pageIndex] = [element];

            sumHeight = curRowHeight;
          }else {
            if (!pageImageArr[pageIndex]){
              pageImageArr[pageIndex] = [element];
            }else {
              pageImageArr[pageIndex].push(element);
            }
          }
        });
        console.log(pageImageArr);
        if (execute){
          that.optionData.forEach( (el, ind) =>{
            if ( pageImageArr[ind] ){
              el.picturesData = pageImageArr[ind].flat().map( e =>{
                return {
                  filePath: e.src,
                }
              })
            }else {
              el.picturesData = [];
            }
          });
        }

        if (!execute){
          that.picturesData = [];
          pageImageArr.forEach( (el, index) =>{
            that.picturesData[index] = el.flat().map( e =>{
              return {
                filePath: e.src,
              }
            });
          });
          that.renderPagePicsShow = true;
          that.paginationRefresh();
          console.log(that.picturesData);
        }

        // 考虑如果图片总长度高于左边长度时
        if (pageImageArr.length > that.optionData.length && execute){
          that.extraPicsArr = pageImageArr.slice(that.optionData.length);
          that.extraPicsInitArr = that.extraPicsArr.flat(2).map( el =>{
            return {
              filePath: el.src,
            }
          });
          that.previewPagePicsShow = true;
          that.$nextTick( () =>{
            // 再次计算
            that.calculatePics('.previewPagePics',false);
          })
        }
        console.log(that.optionData);
        that.renderPageShow = true;
        that.paginationRefresh();
      })
    },
    calculateTable(){
      const that = this;
      // 单页高度
      const pageHeight = 756;
      // 计算公共头部高度
      let commonHeadH = this.getDomHeight('#commonHead');
      // 工序Bom
      let materialBomH = this.getDomHeight('#bomData');
      // 设备资源
      let deviceSourceH = this.getDomHeight('#sourceData');
      // 程序
      let programH = this.getDomHeight('#gramData');
      // 操作步骤
      let stepH = this.getDomHeight('#stepData');
      let spilitArr = []; // [{id: [tr,tr]},{}]
      let spilitArrIndex = 0;
      let startIndex = 0;
      let bufferHeight = 0; // 除第一页外每一页都要留一个页头高度出来
      // 计算分页
      // if ( pageHeight < (commonHeadH + materialBomH + deviceSourceH + programH + stepH) ){
        // 获取所有tr
        let allTrDom = document.querySelectorAll('.sopmake-preview-page__content tr');
        allTrDom = Array.from(allTrDom);
        allTrDom.forEach( (element, index) =>{
          let curId = element.parentNode.parentNode.getAttribute('id');
          if (index === 0){
            spilitArr[0] = {};
            spilitArr[0][curId] = [element];
            return;
          }
          const curTrArr = allTrDom.slice(startIndex,index+1);
          const curTrHeightArr = curTrArr.map( el => el.offsetHeight);
          let sumH = curTrHeightArr.reduce((total, num) => total + num);
          if (spilitArrIndex > 0){
            bufferHeight = 26;
          }
          // 把符合条件的tr放到数组里
          if ( (sumH + commonHeadH) > (pageHeight + bufferHeight) ){
            spilitArrIndex++;
            startIndex = index;
            if (!spilitArr[spilitArrIndex]){
              spilitArr[spilitArrIndex] = {};
              spilitArr[spilitArrIndex][curId] = [element];
            }
          }else{
            if (!spilitArr[spilitArrIndex]){
              spilitArr[spilitArrIndex] = {};
              spilitArr[spilitArrIndex][curId] = [element];
            }else {
              if ( spilitArr[spilitArrIndex][curId] ){
                spilitArr[spilitArrIndex][curId].push(element);
              }else {
                spilitArr[spilitArrIndex][curId] = [element];
              }
            }
          }
        });
        // console.log(spilitArr);
      // }
      // 遍历 spilitArr 组装每页的数据
      spilitArr.forEach( (element, index) =>{
        that.optionData[index] = {};
        for (let id in element) {
          that.optionData[index][id] = [];
          let startIndexNow = 0;
          let endIndex = 0;
          const curIdData = element[id];
          if (curIdData[0].getAttribute('data-index') === 'theadIndex'){
            startIndexNow = Number(curIdData[1].getAttribute('data-index'));
          }else{
            startIndexNow = Number(curIdData[0].getAttribute('data-index'));
          }
          endIndex = Number(curIdData[curIdData.length - 1].getAttribute('data-index'));
          that.optionData[index][id] = that.options[id].slice(startIndexNow,endIndex + 1);
          // that.optionData[index][id] = that.optionMapData[id].slice(startIndexNow,endIndex + 1);
        }
      });
      if (spilitArr.length === 0){
        that.optionData = [];
      }
      console.log(that.optionData);
    },
    printClick(){
      printJS({
        printable: this.$refs.renderPage.outerHTML,
        type: 'raw-html',
      });
    },
    paginationChange(){
      let ypos = (this.current - 1) * 782 ;
      document.querySelector('.poros-modal-body').scrollTo(0,ypos)
    },
  }
}
</script>
<style lang="less">
.previewPageWrap{
  height: 0;
  overflow: hidden;
}
#renderPage{
  .sopmake-preview-page{
    margin-top: 20px;
    background: #fff;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.55);
    margin-left: auto;
    margin-right: auto;
  }
  >div:first-child{
    margin-top: 0;
  }
}
</style>